package richrail.tools;

import richrail.RichRailApp;
import richrail.domain.TrainUnit;

public class CommandParser {
	
	private static CommandParser instance;
	private RichRailApp app;
	
	private static final String 
		NEW 		= "new",
		DELETE		= "delete",
		REMOVE 		= "remove",
		ADD			= "add",
		TO			= "to",
		FROM		= "from",
		TYPE 		= "("+TrainUnit.TRAIN+"|"+TrainUnit.WAGON+")",
		WHITESPACE 	= "(\t| |\r|\n|\u000C)+",
		ID 			= "[a-z][a-z|0-9]*",
		NUMBER		= "[0-9]+",
		NUMSEATS	= "numseats",
		GETNUMSEATS = "getnumseats",
		INCORRECT	= "command is incorrect";
	
	private static final String 
		NEWCOMMAND	= NEW+WHITESPACE+TYPE+WHITESPACE+ID,
		NEWCOMMANDSEATS	= NEWCOMMAND+WHITESPACE+NUMSEATS+WHITESPACE+NUMBER,
		ADDCOMMAND	= ADD+WHITESPACE+ID+WHITESPACE+TO+WHITESPACE+ID,
		DELCOMMAND 	= DELETE+WHITESPACE+TYPE+WHITESPACE+ID,
		REMCOMMAND	= REMOVE+WHITESPACE+ID+WHITESPACE+FROM+WHITESPACE+ID,
		GETCOMMAND	= GETNUMSEATS+WHITESPACE+TYPE+WHITESPACE+ID;

	public static CommandParser getInstance() {
		if(instance == null) {
			instance = new CommandParser();
		}
		return instance;
	}
	
	public void setApp(RichRailApp app) {
		this.app = app;
	}
	
	public void parseCommand(String command) {
		command = command.trim();
		String[] commandParts = command.split(WHITESPACE);
		
		if(command.equals("")) return;
		
		// NEW
		if(command.matches(NEWCOMMAND)) 
		{
			app.getGarage().newUnit(commandParts[1],commandParts[2]);
		} 
		// NEW + NUMSEATS
		else if(command.matches(NEWCOMMANDSEATS)) 
		{
			int number = Integer.parseInt(commandParts[4]);
			app.getGarage().newUnit(commandParts[1],commandParts[2],number);
		}
		// DELETE
		else if(command.matches(DELCOMMAND)) {
			app.getGarage().delete(commandParts[1],commandParts[2]);
		}
		// ADD
		else if(command.matches(ADDCOMMAND)) {
			app.getGarage().addWagonToTrain(commandParts[1],commandParts[3]);
		}
		// REMOVE
		else if(command.matches(REMCOMMAND)) {
			app.getGarage().removeWagonFromTrain(commandParts[1],commandParts[3]);
		}
		// NUMSEATS
		else if(command.matches(GETCOMMAND)) {
			app.getGarage().getNumSeats(commandParts[1],commandParts[2]);
		}
		// NONE
		else {
			Logger.getInstance().log(INCORRECT);
		}
	}
}
